package com.xmy.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * 求和计算的任务！
 * 如何使用ForkJoin
 * 1. ForkJoinPool 通过它来执行
 * 2. 计算任务ForkJoinPool.execute(ForkJoinTask task)
 * 3. 自定义的计算类要继承ForkJoinTask
 */
public class CountTask extends RecursiveTask<Long> {//RecursiveTask  递归任务
    private long start;
    private long end;

    private final long THRESHOLD=10000; //阈值

    public CountTask(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum = 0;
        boolean canCompute = (end-start)<=THRESHOLD;
        if (canCompute){
            for (long i = start; i <= end; i++) {
                sum+=i;
            }
            return sum;
        }else {
            long mid = (start+end)/2; //中间值
            CountTask task1 = new CountTask(start,mid);// 拆分任务
            CountTask task2 = new CountTask(mid+1,end);// 拆分任务
            //将拆分后的子任务，压入ForkJoinWorkerThread线程的工作队列中
            task1.fork();
            task2.fork();
            // 返回子任务的结果
            return task1.join()+task2.join();
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        ForkJoinPool forkJoinPool = new ForkJoinPool();
//        CountTask countTask = new CountTask(1,10000000);
//        ForkJoinTask<Long> forkJoinTask = forkJoinPool.submit(countTask);
//        System.out.println(forkJoinTask.get());

        LongStream.rangeClosed(1,10_0000_0000).parallel().reduce(0,Long::sum);
    }
}
